﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MyExtension
{
    /// <summary>
    /// 
    /// </summary>
    public static class ModelExtension
    {
        /// <summary>
        /// 数据拷贝
        /// </summary>
        /// <param name="origin">源对象</param>
        /// <param name="target">目标对象</param>
        public static T2 ToModel<T1, T2>(this T1 origin) 
            where T1 : new()
            where T2 : new()
        {
            try
            {
                T2 target = new();
                if (origin != null && target != null)
                {
                    PropertyInfo[] targetProperties = target.GetType().GetProperties();
                    PropertyInfo[] originProperties = origin.GetType().GetProperties();
                    foreach (PropertyInfo originProperty in originProperties)
                    {
                        foreach (PropertyInfo targetProperty in targetProperties)
                        {
                            if (originProperty == null 
                                || !string.Equals(originProperty.Name, targetProperty.Name, StringComparison.CurrentCultureIgnoreCase) 
                                || !targetProperty.CanWrite)
                            {
                                continue;
                            }
                            object originProValue = originProperty.GetValue(origin, null);
                            if (originProValue == null || targetProperty.PropertyType.IsInstanceOfType(originProValue))
                            {
                                targetProperty.SetValue(target, originProperty.GetValue(origin, null), null);
                            }
                        }
                    }
                }
                return target;
            }
            catch(Exception)
            {
                throw;
            }
        }

    }
}
